package org.lql.algo.codecrush.week010;

import org.lql.algo.common.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: liangqinglong
 * @date: 2025-08-30 15:41
 * @description: LCR 153. 二叉树中和为目标值的路径 <a href="https://leetcode.cn/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/description/">...</a>
 **/
public class PathTarget {

	public List<List<Integer>> pathTarget(TreeNode root, int target) {
		List<List<Integer>> res = new ArrayList<>();
		dfs(root, target, new ArrayList<>(), res);
		return res;
	}

	private void dfs(TreeNode node, int target, List<Integer> path, List<List<Integer>> res) {
		if (node == null) return;

		path.add(node.val);
		target -= node.val;

		// 到达叶子节点并且路径和满足条件
		if (node.left == null && node.right == null && target == 0) {
			res.add(new ArrayList<>(path));
		} else {
			dfs(node.left, target, path, res);
			dfs(node.right, target, path, res);
		}

		// 回溯
		path.remove(path.size() - 1);
	}
}
